<template>
  <div class="app-container">
    <help :show-help="showHelp" />
    <div class="filter-container">
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        style="width: 120px"
        clearable
        class="filter-item"
        @change="handleFilter"
        @clear="clearStatus"
      >
        <el-option
          v-for="item in statusMap"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        class="filter-item"
        v-model="listQuery.start"
        value-format="yyyy-MM-dd"
        type="date"
        style="margin-left: 10px"
        @change="handleFilter"
        placeholder="开始日期">
      </el-date-picker>
      -
      <el-date-picker
        class="filter-item"
        v-model="listQuery.end"
        type="date"
        @change="handleFilter"
        value-format="yyyy-MM-dd"
        placeholder="结束日期">
      </el-date-picker>
    </div>
    <div class="filter-container">
      <el-input
        v-model="listQuery.id"
        placeholder="拼团ID"
        style="width: 200px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.user_id"
        placeholder="团长ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-input
        v-model="listQuery.fans_id"
        placeholder="粉丝ID"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
        @blur="handleFilter"
      />
      <el-button
        v-waves
        type="primary"
        icon="el-icon-search"
        class="filter-item"
        style="margin-left: 10px;"
        @click="handleFilter"
      >搜 索</el-button>
      <el-button
        v-waves
        type="success"
        icon="el-icon-refresh"
        class="filter-item"
        style="margin-left: 10px;"
        @click="clearFilter"
      >清除筛选</el-button>
    </div>
    <div class="filter-container">
      <el-button
        v-waves
        type="success"
        icon="el-icon-download"
        class="filter-item"
        size="small"
        plain
        :loading="listLoading"
        @click="handleExport"
      >导出 Excel</el-button>
      <el-button
        v-waves
        type="success"
        class="filter-item"
        size="small"
        plain
        @click="showHelp = !showHelp"
      >{{ showHelp ? '关闭帮助' : '显示帮助' }}</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :border="false"
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column v-if="listShow.id" sortable="custom" prop="id" label="团ID" width="100">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="团长" sortable="custom" prop="user_id" width="100">
        <template slot-scope="{row}">
          <span>{{ row.user_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品" align="left" width="100">
        <template slot-scope="{row}">
          <div class="main-image">
            <el-image :src="row.product.mainImage.thumbnail_path" lazy :fit="'cover'"
                      :preview-src-list="[row.product.mainImage.path]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="400">
        <template slot-scope="{row}">
          <span>{{ row.product.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" width="120" align="center">
        <template slot-scope="{row}">
          <span>{{ row.fans.length }}</span>
        </template>
      </el-table-column>
      <el-table-column label="随机团" width="80">
        <template slot-scope="{row}">
          <span>{{ +row.is_random ? '是': '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" sortable="custom" prop="status" align="center">
        <template slot-scope="{row}">
          <span>{{ row.status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="listShow.date" label="创建时间" sortable="custom" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="100"
        fixed="right"
      >
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" @click="handleView(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="listQuery.total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      @pagination="refresh"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import api from '@/api'
import Help from './components/Help'
import config from '@/config'

const initQuery = {
  status: config.group.ALL,
  page: 1,
  pageSize: 10,
  total: 0,
  sort: '+id'
}

export default {
  name: 'OrderList',
  components: {
    Pagination,
    Help
  },
  directives: { waves },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.group.statusText(+status)
    },
    // typeText(v) {
    //   return +v === 1 ? '拼团订单' : '普通订单'
    // }
  },
  data() {
    return {
      // 状态
      status: {},
      // 状态
      statusMap: [
        { value: -1, label: '全部' },
        { value: 1, label: '正在进行中' },
        { value: 2, label: '已完成' },
        { value: 0, label: '待支付' },
      ],
      // 显示帮助提示
      showHelp: false,
      listLoading: false,
      list: [],
      listQuery: {},
      defaultSort: {},
      // selectionList: [],
      // 显示控制
      listShow: {
        id: true,
        date: true
      }
    }
  },
  created() {
    this.parseQuery()
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleView(item) {
      // 查看详情
      this.$router.push(`/order/group-view/${item.id}`)
    },
    /**
     * 清除状态
     */
    clearStatus() {
      // this.listQuery.status = config.order.ALL
      this.listQuery.status = null
    },
    /**
     * 查询高亮
     */
    wrapperKeyword(k, v) {
      const highlight = value => {
        return `<span style="color: #1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      }
      return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
    },
    /**
     * 获取数据列表
     */
    getList() {
      this.listLoading = true
      // 状态需要处理
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      api.order.groupList({ ...this.listQuery }).then(response => {
        const { data } = response
        this.list = data.list
        this.listQuery.total = +data.totalCount
        this.listLoading = false
        this.list.forEach(x => {
          // 搜索高亮
          // x.snWrapper = this.wrapperKeyword('sn', x.sn)
        })
      }).finally(() => {
        this.listLoading = false
      })
    },
    /**
     * 排序
     * @param data
     */
    sortChange(data) {
      const sortBy = (prop, order) => {
        if (prop && order === 'ascending') {
          this.listQuery.sort = `+${prop}`
        } else if (prop && order === 'descending') {
          this.listQuery.sort = `-${prop}`
        } else {
          this.listQuery.sort = ''
        }
      }
      const { prop, order } = data
      sortBy(prop, order)
      this.handleFilter()
    },
    /**
     * 刷新
     */
    refresh() {
      this.$router.push({
        path: '/order/group',
        query: this.listQuery
      })
    },
    /**
     * 过滤(筛选)
     */
    handleFilter() {
      // this.listQuery.page = 1
      this.refresh()
    },
    /**
     * 清除筛选
     */
    clearFilter() {
      this.listQuery = Object.assign({}, initQuery)
      this.defaultSort = {}
      this.refresh()
    },
    /**
     * 处理筛选条件
     */
    parseQuery() {
      const query = Object.assign({}, this.$route.query)
      let sort = '-id'
      this.listQuery = Object.assign({}, { ...initQuery, sort })
      if (Object.keys(query).length > 0) {
        // 注意这里的类型转换
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.total && (query.total = +query.total)
        query.status && (query.status = +query.status)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...this.listQuery, ...query }
      this.status = config.order
    },
    /**
     * 导出
     */
    async handleExport() {
      const formatJson = (filterVal, jsonData) => {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'status') {
            return config.group.statusText(+v['status'])
          }
          if (j === 'product') {
            return v['product']['title']
          }
          if (j === 'fans') {
            return v['fans'].length
          }
          if (j === 'is_random') {
            return +v['is_random'] === 1 ? '是' : ''
          }
          return v[j]
        }))
      }
      this.listLoading = true
      if (this.listQuery.status === '') {
        this.listQuery.status = initQuery.status
      }
      const response = await api.order.groupList({ ...this.listQuery, export: true })
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['ID', '团长ID', '商品', '参与人数', '状态', '创建时间', '是否为随机团']
        const filterVal = ['id', 'user_id', 'product', 'fans', 'status', 'create_time', 'is_random']
        const list = response.data
        const data = formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '拼团列表'
        })
      })
      this.listLoading = false
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.main-image {
  //width: 100px;
  //height: 100px;
}
</style>
